﻿/************************************************
* Copyright (C) 2011 东北农业大学(NEAU) 版权所有。
* 文件名：
* 版本号：
* 文件功能描述：
* 作者：
* 创建日期:
* 版本号：
* 修改人：
* 修改日期：
* 修改描述：
************************************************/
Ext.BLANK_IMAGE_URL = "/script/ext/resources/images/s.gif";
Ext.onReady(function () {
    var modelid = jQuery.query.get("modelid");
    /*初始化快速提示*/
    Ext.QuickTips.init();
    /*将提示显示在form属性旁边*/
    Ext.form.Field.prototype.msgTarget = "qtip";

    /*定义数据模型*/
    var KnowledgeInfo = new Ext.data.Record.create([
                        { name: 'ID', type: 'int', mapping: 'ID' },
                        { name: 'Title', mapping: 'Title' },
                        { name: 'AddTime', type: 'date', mapping: 'AddTime' },
                        { name: 'ContentText', mapping: 'ContentText' },
                        { name: 'TypeID', type: 'int', mapping: 'TypeID' },
                        { name: 'AddUser', type: 'string', mapping: 'AddUser' }
                        ]);
    /*创建数据源*/
    var KnowledgegroupStore = new Ext.data.GroupingStore({
        proxy: new Ext.data.HttpProxy({ url: "../Default/server/notice/noticeList.aspx?type=3&r=" + new Date().getTime() }),
        reader: new Ext.data.JsonReader({ totalProperty: "Count", root: "List" }, KnowledgeInfo),
        sortInfo: { field: 'AddTime', direction: 'DESC' }
    });
    /*设置每页条数*/
    var pageSize = 20;
    var cookiePageSize = parseInt(Ext.util.Cookies.get("pageSize"));
    if (cookiePageSize) { pageSize = cookiePageSize; }

    /*创建下[每页行数]拉框*/
    var comboBox = new Ext.form.ComboBox({
        width: 50,
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        title: "每页行数",
        emptyText: pageSize,
        store: new Ext.data.ArrayStore({ id: 0, fields: ['myId', 'displayText'], data: [[10, 10], [20, 20], [30, 30], [50, 50], [100, 100]] }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    comboBox.on("select", function (combo, record, index) {
        Ext.util.Cookies.set("pageSize", record.id);
        window.location.reload();
    });

    /*加载数据源*/
    KnowledgegroupStore.load({ params: { start: 0, limit: pageSize} });

    /*创建选择列模型*/
    var sm = new Ext.grid.CheckboxSelectionModel();

    /*定义列模型*/
    var cm = new Ext.grid.ColumnModel([
            sm,
            { id: 'id', header: '编号', dataIndex: 'ID', width: 60, sortable: true },
            { id: 'title', header: '标题', dataIndex: 'Title', width: 100, sortable: true },
            { id: 'addtime', header: '发布时间', dataIndex: 'AddTime', width: 140, sortable: true, renderer: Ext.util.Format.dateRenderer('Y-m-d') },
            { id: 'adduser', header: '发布人', dataIndex: 'AddUser', width: 230, sortable: true }
            ]);

    /*创建数据窗格*/
    var grid = new Ext.grid.GridPanel({
        region: "center",
        margins: "5 5 0 5",
        border: true,
        store: KnowledgegroupStore,
        autoExpandColumn: "title",
        loadMask: { msg: '正在努力的加载，请稍等片刻..' },
        view: new Ext.grid.GroupingView(),
        cm: cm,
        sm: sm,
        tbar: [{
            iconCls: 'icon-add',
            text: '添加',
            value: 0,
            handler: function (btn) {
                viewport.items.get(1).expand();
                form.setTitle("信息添加");
                form.getForm().reset();
            }
        }, {
            ref: '../removeBtn',
            iconCls: 'icon-del',
            text: '删除',
            disabled: true,
            handler: function () {
                Ext.MessageBox.confirm("确认提示", "确认要删除所选行数据？", function (btn) {
                    if (btn == "yes") {
                        var s = grid.getSelectionModel().getSelections();
                        var delR = new Array();
                        var delRid = new Array();
                        for (var i = s.length - 1; i >= 0; i--) {
                            var r = s[i];
                            if (r.get('ID') != undefined) { delRid.push(r.get('ID')); delR.push(r); }
                        }
                        Ext.Ajax.request({
                            url: "server/notice/noticeDel.aspx",
                            method: 'POST',
                            params: { id: delRid, modelid: modelid },
                            success: function (response) {
                                var json = Ext.util.JSON.decode(response.responseText);
                                if (json.success) {
                                    for (var i = 0; i < delR.length; i++) {
                                        if (json.ids.valueOf(delR[i].get('ID'))) { KnowledgegroupStore.remove(delR[i]) }
                                    }
                                    Ext.Msg.alert("提示", "已删除" + json.count + "行<br/>" + json.msg);
                                } else {
                                    Ext.Msg.alert("错误", json.msg);
                                }
                            }
                        });
                    }
                });
            }
        }, {
            ref: '../viewBtn',
            iconCls: 'icon-view',
            text: '查看',
            disabled: true,
            handler: function () {
                var s = grid.getSelectionModel().getSelections();
                window.open('server/notice/noticeDetail.aspx?id2=' + s[0].get("ID"));
            }
        }],
        bbar: new Ext.PagingToolbar({
            store: KnowledgegroupStore,
            pageSize: pageSize,
            displayInfo: true,
            prependButtons: true,
            items: [comboBox],
            displayMsg: "本页显示第{0}条到第{1}条数据，共{2}条",
            emptyMsg: "暂无记录"
        })
    });

    var form = new Ext.form.FormPanel({
        region: 'south',
        title: "信息添加",
        margins: "5",
        collapsible: true,
        frame: true,
        split: false,
        height: 240,
        labelAlign: "right",
        labelWidth: 70,
        buttonAlign: "center",
        items: [{
            layout: 'column', //定义为列模式
            items: [{
                columnWidth: .2, //显示为第一列的宽度33%
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    fieldLabel: '信息编号',
                    labelStyle: 'color:red',
                    minLength: 6,
                    minLengthText: "长度不能小于6个字符",
                    maxLength: 20,
                    maxLengthText: "长度超过了20个字符",
                    name: 'ID',
                    allowBlank: false,
                    blankText: '信息编号不能为空',
                    regex: /[\u4e00-\u9fa5]/,
                    regexText: "只能输入中文!",
                    anchor: '100%',
                    value: 0,
                    disabled: true
                }]
            }, {
                columnWidth: .6,
                layout: 'form',
                items: [{
                    xtype: 'textfield', //显示为输入框
                    fieldLabel: '信息标题', //标签名称 
                    labelStyle: 'color:red', //标题的样式
                    minLength: 2,
                    minLengthText: "长度不能小于2个字符",
                    maxLength: 50,
                    maxLengthText: "长度超过了50个字符",
                    name: 'Title', //
                    allowBlank: false, //不允许为空
                    blankText: '信息标题不能为空', //不允许为空给的提示
                    regex: /[\u4e00-\u9fa5]/, //正则表达式在/...../之间.
                    regexText: "只能输入中文!", //正则表达式错误提示
                    anchor: '100%'
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'datefield',
                    fieldLabel: '发布时间',
                    name: 'AddTime',
                    value: new Date(),
                    format: "Y-m-d",
                    anchor: '100%'
                }]
            }]
        }, new Ext.form.HtmlEditor({
            fieldLabel: '信息内容', //标签名称 
            anchor: '100%',
            height: 140,
            name: "ContentText"
        })],
        buttons: [{
            text: "确定", handler: function () {
                if (form.form.isValid()) {
                    var params = {
                        modelid: modelid,
                        ID: form.getForm().findField("ID").getValue(),
                        Title: form.getForm().findField("Title").getValue(),
                        AddTime: form.getForm().findField("AddTime").getValue(),
                        ContentText: form.getForm().findField("ContentText").getValue(),
                        TypeID: 3
                    };
                    Ext.Ajax.request({
                        url: "server/notice/noticeAdd.aspx",
                        params: params,
                        success: function (response) {
                            var json = Ext.util.JSON.decode(response.responseText);
                            if (json.success) {
                                Ext.Msg.alert("请求成功", json.msg, function () {
                                    KnowledgegroupStore.load({ params: { start: 0, limit: pageSize} });
                                });
                                form.getForm().reset();
                            } else {
                                Ext.Msg.alert("错误", json.msg);
                            }
                        },
                        failure: function (response) { Ext.Msg.alert("请求失败", response.responseText); }
                    });
                }
            }
        }, {
            text: "重置",
            handler: function () {
                form.getForm().reset();
            }
        }]
    });

    /*创建页面布局*/
    var viewport = new Ext.Viewport({
        layout: 'border',
        items: [grid, form]
    }); /*布局加载*/viewport.doLayout();
    viewport.items.get(1).collapse();

    /*延时加载*/
    setTimeout(function () { Ext.get('loading').remove(); Ext.get('loading-mask').fadeOut({ remove: true }); }, 400);

    /*有选择行启用删除按钮*/
    grid.getSelectionModel().on('selectionchange', function (sm) {
        grid.removeBtn.setDisabled(sm.getCount() < 1);
        grid.viewBtn.setDisabled(sm.getCount() < 1 || sm.getCount() > 1);
    });
    grid.on('rowdblclick', function (g, index, e) {
        viewport.items.get(1).expand();
        var r = g.getSelectionModel().getSelected();
        if (r != null) {
            form.setTitle("信息编辑");
            form.form.loadRecord(new KnowledgeInfo({ 'ID': r.get("ID"), 'Title': r.get("Title"), 'ContentText': r.get("ContentText"), 'AddTime': r.get("AddTime") }));
            form.doLayout();
        }
    });
});